//
//  DownloadManager.m
//  WOFishingBoat
//
//  Created by 郑逸凯 on 2019/1/10.
//  Copyright © 2019年 郑逸凯. All rights reserved.
//

#import "DownloadManager.h"
#import <Photos/Photos.h>

@interface DownloadManager ()

@property (nonatomic,strong)dispatch_queue_t downloadQueue;
@end

@implementation DownloadManager

+ (instancetype)sharedInstance {
    static DownloadManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
        _sharedInstance.downloadQueue = dispatch_queue_create("wo_download_image_queue", DISPATCH_QUEUE_CONCURRENT);
    });
    return _sharedInstance;
}

- (void)download:(NSArray *)photoArray progress:(ImageDownloaderProgressBlock)progressBlock completionHandler:(void (^)(NSArray *errorArray))completionHandler {
    dispatch_semaphore_t semaphore_t = dispatch_semaphore_create(0);
    __block NSMutableArray *mutableErrorArray = [NSMutableArray array];
    NSLog(@"zykdownload - %li",photoArray.count);
    dispatch_async(self.downloadQueue, ^{
        for (NSInteger i = 0; i < photoArray.count; i++) {
            MWPhoto *photo = [photoArray objectAtIndex:i];
            NSLog(@"zykdownload 开始下载- %li",i);
            void (^downloadCompletionHandler)(NSError * error) = ^(NSError * _Nonnull error) {
                NSLog(@"zykdownload 存储相册成功- %li",i);
                if (error) {
                    [mutableErrorArray addObject:error];
                }
                dispatch_semaphore_signal(semaphore_t);
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (progressBlock) {
                        progressBlock(i+1,photoArray.count);
                    }
                    if (i == photoArray.count - 1) {
                        if (completionHandler) {
                            completionHandler(mutableErrorArray);
                        };
                        
                    }
                });
            };
            if (photo.isVideo) {
                [self downloadVideoWithUrl:photo.videoURL completionHandler:^(NSString *path) {
                    NSLog(@"zykdownload 下载视频成功- %li",i);
                    [self saveVideoWithPath:path completionHandler:downloadCompletionHandler];
                }];
            }else {
                [photo downloadImageCompletionHandler:^(UIImage * image) {
                    NSLog(@"zykdownload 下载相册成功- %li",i);
                    [self saveImage:image completionHandler:downloadCompletionHandler];
                }];
            }
            
            dispatch_semaphore_wait(semaphore_t,dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC));
        }
    });
    
}

- (void)saveImage:(UIImage *)image completionHandler:(void (^)(NSError * _Nonnull))completionHandler {
    if (!image) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler([NSError errorWithDomain:@"存入相册失败" code:-1 userInfo:nil]);
            };
        });
        return;
    }
    PHAssetCollection *desCollection = nil;
    PHFetchResult <PHAssetCollection*>*result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collect in result) {
        if ([collect.localizedTitle isEqualToString:YA_ALBUM_NAME]) {
            desCollection = collect;
        }
    }
    if (desCollection == nil) {
        __block NSString *colID = nil;
        NSError *error = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            colID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:YA_ALBUM_NAME].placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error];
        if (error) {
            NSLog(@"创建相册: %@ 失败",colID);
        }
        desCollection = [[PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[colID] options:nil] firstObject];
    }
    __block PHObjectPlaceholder *placeholderAsset=nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        placeholderAsset = changeRequest.placeholderForCreatedAsset;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                
                PHAsset *asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[placeholderAsset.localIdentifier] options:nil] lastObject];
                
                [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:desCollection] addAssets:@[asset]];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                NSError *newError = nil;
                if (!success) {
                    newError = [NSError errorWithDomain:@"存入相册失败" code:-1 userInfo:nil];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completionHandler) {
                        completionHandler(newError);
                    };
                });
            }];
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completionHandler) {
                    completionHandler([NSError errorWithDomain:@"存入相册失败" code:-1 userInfo:nil]);
                };
            });
        }
        
    }];
    
}

- (void)saveVideoWithPath:(NSString *)path completionHandler:(void (^)(NSError * _Nonnull))completionHandler {
    if (!path) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler([NSError errorWithDomain:@"存入相册失败" code:-1 userInfo:nil]);
            };
        });
        return;
    }
    PHAssetCollection *desCollection = nil;
    PHFetchResult <PHAssetCollection*>*result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collect in result) {
        if ([collect.localizedTitle isEqualToString:YA_ALBUM_NAME]) {
            desCollection = collect;
        }
    }
    if (desCollection == nil) {
        __block NSString *colID = nil;
        NSError *error = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            colID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:YA_ALBUM_NAME].placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error];
        if (error) {
            NSLog(@"创建相册: %@ 失败",colID);
        }
        desCollection = [[PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[colID] options:nil] firstObject];
    }
    __block PHObjectPlaceholder *placeholderAsset=nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//        NSString *str = [YAEncode encodeString:path];
        PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:path]];
        placeholderAsset = changeRequest.placeholderForCreatedAsset;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                
                PHAsset *asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[placeholderAsset.localIdentifier] options:nil] lastObject];
                
                [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:desCollection] addAssets:@[asset]];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                NSError *newError = nil;
                if (!success) {
                    newError = [NSError errorWithDomain:@"存入相册失败" code:-1 userInfo:nil];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completionHandler) {
                        completionHandler(newError);
                    };
                });
            }];
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completionHandler) {
                    completionHandler([NSError errorWithDomain:@"存入相册失败" code:-1 userInfo:nil]);
                };
            });
        }
        
    }];
    
}



- (void)downloadVideoWithUrl:(NSURL *)url completionHandler:(void (^)(NSString * path ))completionHandler {
    NSString *urlPath = url.absoluteString;
    NSString *fileName = urlPath.lastPathComponent;
    NSString *localDir = [NSTemporaryDirectory() stringByAppendingPathComponent:@"vimedia"];
    NSString *localFilePath = [NSString stringWithFormat:@"%@/%@",localDir,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    
    BOOL isDirExist = [fileManager fileExistsAtPath:localDir isDirectory:&isDir];
    if (!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:localDir withIntermediateDirectories:YES attributes:nil error:nil];
        
        if(!bCreateDir){
            
            NSLog(@"Create Audio Directory Failed.");
            
        }
        
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePath]) {
        if (completionHandler) {
            completionHandler(localFilePath);
        }
    }else {
        NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (completionHandler) {
                if (!error) {
                    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:localFilePath] error:nil];
                    completionHandler(localFilePath);
                }else {
                    completionHandler(nil);
                }
            }
        }];
        [task resume];
    }
    
}

#pragma mark - 相册权限
- (BOOL)authorizationStatusAuthorized {
    NSInteger status = [PHPhotoLibrary authorizationStatus];
    if (status == 0) {
        /**
         * 当某些情况下AuthorizationStatus == AuthorizationStatusNotDetermined时，无法弹出系统首次使用的授权alertView，系统应用设置里亦没有相册的设置，此时将无法使用，故作以下操作，弹出系统首次使用的授权alertView
         */
        [self requestAuthorizationWithCompletion:nil];
    }
    
    return status == 3;
}

- (void)requestAuthorizationWithCompletion:(void (^)(void))completion {
    void (^callCompletionBlock)(void) = ^(){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion();
            }
        });
    };
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            callCompletionBlock();
        }];
    });
}


@end
